package com.twu.biblioteca;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class Menu implements Options {

    private ArrayList<String> iterms = new ArrayList<String>();
    private ArrayList<Options> subOptions = new ArrayList<Options>();
    public int selectedOption;

    public Menu() {
        iterms.add("==== Menu Options ====");
        iterms.add("Find a book");
        iterms.add("My library");
        iterms.add("Exit");
        subOptions.add(new FindABook());
        subOptions.add(new MyLibrary());
        subOptions.add(new Exit());
    }

    @Override
    public void printOptions() {
        System.out.println(iterms.get(0));
        for (int i = 1; i < iterms.size(); i++) {
            System.out.println("  " + i + ". " + iterms.get(i));
        }
    }

    @Override
    public void setSelectedOption(int selectedOption) {
        this.selectedOption = optionsValidation(selectedOption);
    }

    @Override
    public int getSelectedOptionFromInput() {
        int index = 0;
        System.out.print("\nInput the Index of the option on menu please:");
        String input = getInput();
        try {
            index = Integer.parseInt(input);
        } catch (NumberFormatException e) {
            index = getSelectedOptionFromInput();
        }
        return index;
    }

    @Override
    public Options goToSelectedOption() {
        subOptions.get(selectedOption - 1).printOptions();
        return subOptions.get(selectedOption - 1);
    }

    private int optionsValidation(int selectedOption) {
        int validSelectedOption = selectedOption;
        while (validSelectedOption < 1 || validSelectedOption >= iterms.size()) {
            System.out.println("       Select a valid option!!");
            validSelectedOption = optionsValidation(getSelectedOptionFromInput());
        }
        return validSelectedOption;
    }

    private static String getInput() {
        try {
            BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
            return bufferRead.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}